import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { tranListToTreeData } from '@/utils'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    route: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, username) => {
    state.username = username
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  routes: (state, name) => {
    state.route = name
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const { data } = response
        // 这里需要调整，读取token的深浅不一致
        // 触发mutations
        commit('SET_TOKEN', data.token)
        // 存储到本地
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户资料
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        const res = tranListToTreeData(data.permission_menu_list, 0)
        console.log(res)
        commit('routes', dodata(res))
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        // 读取的字段可能不一致
        // console.log(data.userinfo)
        const { username, avatar } = data.userinfo
        // console.log(username)
        // console.log(avatar)
        // 设置给state
        commit('SET_NAME', username)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出操作
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       // 移除token，先移除token
  //       removeToken()
  //       // 重置路由
  //       resetRouter()
  //       // 重置state数据
  //       commit('RESET_STATE')
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  logout({ commit }) {
    removeToken()
    commit('RESET_STATE')
    // 重置路由实例对象
    resetRouter()
    // 将权限模块里面routes变成静态路由
    // 兄弟模块之间的调用，需要从根模块开始调用 mutation
    // commit('permission/setRoutes', [], { root: true })
  },

  // 移除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      // 先移除token
      removeToken()
      // 重置state数据
      commit('RESET_STATE')
      resolve()
    })
  }

}

function dodata(arrs) {
  const arr = []
  arrs.forEach((item) => {
    const obj = {
      path: item.route,
      hidden: item.hidden !== 1,
      redirect: item.redirect,
      children:
        item.children && item.children[0].type === 1
          ? dodata(item.children)
          : [],
      meta: { title: item.permission_name, icon: item.icon }
    }
    arr.push(obj)
  })
  return arr
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

